﻿using SaaS.Core;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using XCore.Redis;

namespace SaaS.Cache.Auths
{
    /// <summary>
    /// 授权缓存基类
    /// </summary>
    public abstract class AuthCacheServiceBase : CacheServiceBase
    {
        protected override int Db => 1;
        /// <summary>
        /// 设置token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="token"></param>
        protected virtual void SetToken(string key, int userId, string token)
        {
            Redis.HashSetAsync(key, userId, token);
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        protected virtual string GetToken(string key, int userId)
        {
            return Redis.HashGet(key, userId);
        }
        /// <summary>
        /// 移除Token
        /// </summary>
        /// <param name="prefix"></param>
        /// <param name="userId"></param>
        protected virtual void RemoveToken(string key, int userId)
        {
            Redis.HashDelete(key, userId);
        }
        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="permissions"></param>
        protected virtual void SetPermission(string key, int userId, IEnumerable<string> permissions)
        {
            key += userId;
            IBatch batch = Redis.CreateBatch();
            batch.KeyDeleteAsync(key);
            foreach (var item in permissions)
            {
                batch.SetAddAsync(key, item);
            }
            batch.Execute();
        }
        /// <summary>
        /// 检查是否拥有此权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="permission"></param>
        /// <returns></returns>
        protected virtual bool IsPermission(string key, int userId, string permission)
        {
            key += userId;
            return Redis.SetContains(key, permission);
        }
        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        protected virtual IEnumerable<string> GetPermission(string key, int userId)
        {
            key += userId;
            foreach (var item in Redis.SetMembers(key))
            {
                yield return item.GetRedisValue<string>();
            }
        }
    }
}
